package com.algorithm.ch1.yjx.array;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @author yuanjianxin
 * @date 2018/8/14 16:33
 */
public class TwoSum {
    public static void main(String[] args) {
        int[] arr1 = {0, 4, 3, 0};
        int target = 0;

        int[] ints = twoSum1(arr1, target);
        System.out.println(Arrays.toString(ints));
    }

    //垃圾代码
    public static int[] twoSum(int[] nums, int target) {
        int[] ret = new int[2];
        for (int i = 0; i < nums.length - 1; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if (i != j && nums[i] + nums[j] == target) {
                    ret[0] = i;
                    ret[1] = j;
                    return ret;
                }
            }
        }
        return ret;
    }

    public static int[] twoSum1(int[] nums, int target) {
        int[] ret = new int[2];
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            int key = target - nums[i];
            if (map.containsKey(key)) {
                ret[0] = map.get(key);
                ret[1] = i;
                break;
            } else {
                map.put(nums[i], i);
            }
        }
        return ret;
    }

}
